"""
资产仓库模块 - 提供资产对象的管理
"""

from typing import Dict, Optional, Any
import logging

from FDAS.data.constants import (
    ASSET_TYPE_STOCK,
    ASSET_TYPE_FUTURE,
    ASSET_TYPE_OPTION,
    ASSET_TYPE_FUND,
    ASSET_TYPE_INDEX,
    ASSET_TYPE_ETF
)

class AssetRepository:
    """资产仓库，用于管理资产对象"""
    
    def __init__(self):
        """初始化资产仓库"""
        self.logger = logging.getLogger(self.__class__.__name__)
        self._assets = {}  # 缓存资产对象
        self._provider = None  # 延迟初始化数据提供者
    
    @property
    def provider(self):
        """获取数据提供者"""
        if self._provider is None:
            # 延迟导入，避免循环依赖
            from FDAS.data.providers import default_provider
            self._provider = default_provider
        return self._provider
    
    def get_asset(self, symbol: str, asset_type: Optional[str] = None) -> Any:
        """
        获取资产对象
        
        参数:
            symbol: 资产代码
            asset_type: 资产类型，如果为None则自动识别
            
        返回:
            资产对象
        """
        # 生成缓存键
        cache_key = f"{symbol}_{asset_type or 'auto'}"
        
        # 检查缓存
        if cache_key in self._assets:
            return self._assets[cache_key]
        
        # 如果未指定资产类型，则自动识别
        if asset_type is None:
            asset_type = self.provider.get_asset_type(symbol)
        
        # 根据资产类型创建对应的资产对象
        from FDAS.data.assets import ASSET_CLASS_MAP
        
        if asset_type in ASSET_CLASS_MAP:
            asset_class = ASSET_CLASS_MAP[asset_type]
            asset = asset_class(symbol, self.provider)
            
            # 缓存资产对象
            self._assets[cache_key] = asset
            
            return asset
        else:
            self.logger.error(f"不支持的资产类型: {asset_type}")
            # 默认返回股票对象
            from FDAS.data.assets.stock import Stock
            asset = Stock(symbol, self.provider)
            
            # 缓存资产对象
            self._assets[cache_key] = asset
            
            return asset
    
    def get_asset_list(self, asset_type: str) -> Any:
        """
        获取资产列表
        
        参数:
            asset_type: 资产类型
            
        返回:
            包含资产代码和名称的DataFrame
        """
        return self.provider.get_asset_list(asset_type)
    
    def clear_cache(self):
        """清除缓存"""
        self._assets = {}
        self.logger.info("资产缓存已清除")